import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { ViteEjsPlugin } from 'vite-plugin-ejs';
import postcssPresetEnv from 'postcss-preset-env';
import legacy from '@vitejs/plugin-legacy';
import { htmlPrerender } from './vite-plugin-html-prerender';
import { mergeLangRouter } from './src/utils/merge-router';

const routes = mergeLangRouter({ symbols: [], requiresAuth: true });

export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd(), '');

    const target = mode === 'production' ? 'http://www.bitv.com/' : 'http://www.dev.bitv-ex.com/';

    return {
        plugins: [
            nodePolyfills(),
            vue(),
            AutoImport({
                imports: ['vue', 'vue-router', 'vuex', 'vue-i18n'],
                resolvers: [
                    ElementPlusResolver({
                        importStyle: 'sass',
                    }),
                ],
                include: [
                    /\.[tj]sx?$/,
                    /\.vue$/, /\.vue\?vue/,
                    /\.md$/,
                ],
                // auto-imports自动引入文件位置
                dts: './src/auto-imports.d.ts',
                eslintrc: {
                    enabled: true,
                    filepath: './.eslintrc-auto-import.json',
                    globalsPropValue: true,
                },
            }),
            // use vant
            Components({
                resolvers: [
                    ElementPlusResolver({
                        importStyle: 'sass',
                    }),
                ],
            }),
            ViteEjsPlugin((viteConfig) => ({
                mode: viteConfig.env.MODE
            })),
            legacy({
                targets: ['defaults', 'not IE 11'],
            }),
            env.PRERENDER ? htmlPrerender({
                staticDir: path.join(__dirname, 'dist'),
                routes,
                minify: {
                    collapseBooleanAttributes: true,
                    collapseWhitespace: true,
                    decodeEntities: true,
                    keepClosingSlash: true,
                    sortAttributes: true
                },
                server: {
                    proxy: {
                        '^/-/h/': {
                            target: 'https://api.bitunu.com/api/',
                            changeOrigin: true,
                            rewrite: (path) => path.replace(/^\/\-\/h\//, '')
                        },
                    },
                },
            }): null,
        ],
        server: {
            host: '0.0.0.0',
            port: '8080',
            open: false,
            cors: true,
            proxy: {
                '^/-/h/': {
                    target: 'https://api.bitunu.com/api/',
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/\-\/h\//, '')
                },
            },
        },
        build: {
            outDir: path.resolve(__dirname, 'dist'),
            assetsDir: 'static',
            cssCodeSplit: true,
            chunkSizeWarningLimit: 2000,
            sourcemap: false,
            assetsInlineLimit: 8 * 1024,
            polyfillDynamicImport: false,
            rollupOptions: {
                output: {
                    chunkFileNames: 'static/js/[name]-[hash].js',
                    entryFileNames: 'static/js/[name]-[hash].js',
                    assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
                }
            },
        },
        css: {
            postcss: {
                // css 兼容
                plugins: [postcssPresetEnv()],
            },
            preprocessorOptions: {
                scss: {
                    additionalData: `@use "@/assets/styles/index.scss" as *;`,
                },
            },
        },
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "./src"),
                //remove i18n waring
                'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
            },
            extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.node', '.scss'],
        },
    };
});
